(function(global){


	
	var url = "?";
	if (typeof (AppItem) == "string" && AppItem.length > 0)
	{
        url += "AppItem=" + AppItem + "&";
    }
    else
	{
        if (typeof (ModelID) == "string" && ModelID.length > 0)
		{
            url += "ModelID=" + ModelID + "&";
        }
    }
    url += "act=check";
    //https://openapi.mypitaya.com
    var config = {
        ajax:{
            // url:'http://localhost:2006/openapi/correct?appkey=22cef02300534158b127a52ade875136',  // 临时解决跨域
            //url:'https://openapi.mypitaya.com/openapi/correct?appkey=22cef02300534158b127a52ade875136', // 报跨域错误
			url:url,//'http://192.168.1.8/ekeframev9/test/getPost.aspx',			
            type:"POST",
            dataType:"json",
            // 错误处理
            error:function(e){
                console.log(e);
            }
        },
        ajaxSuccessCode:"0",  //成功状态码  response.code == ajaxSuccessCode
        svgURL:'icons.svg', // 绝对路径或基于引用此js页面的相对路径
    }

    // 可用方法
    global.writing = {
        config:config,
        parseEditor:parseEditorContent,
        setContentHtml:setContentHtml,
        getContentHtml:getContentHtml,
        getContentText:getContentText,
        clearRightContent:clearRightContent
    }

    /***
     * @arguments
     * callback<function> 调取后发送校验数据，只在验证前调取一次，直接调取或提交HTML片段后调取
     * html<string> 校验HTML片段
     * text<string> 校验文本
     * */
    function beforeVerification(callback,html,text) {
		//alert($("#ID").val());
		save(true);
		//alert(document.location.href);

        // $.ajax({
        //     url:"",
        //     type:'POST',
        //     dataType:"json",
        //     success:function(response){
        //         console.log(response);
        //         // callback && callback();

        //     }
        // })
        console.log( html, text);
        callback && callback();
    }
	// 校验状态
    // message<object>
    //   .length 数组长度（请求次数）
    //   .success 成功次数
    //   .sop 请求进度
    // 当  message.length === message.sop 表示请求结束
    function onMessage(message){


       // console.log(message);

        if( message.length === message.sop ) {
			//alert(message.length + "::" +  message.success);
			if($(".error-list li").length == 0 )
			{
				$(".writingtip").show();
				$(".error-list").hide();
			}
			else
			{
				$(".error-list").show();
			}
			//alert($(".error-list li").length);
            //console.log(`请求完成 \n 成功：${ message.success }\n 失败：${message.length - message.success}`);
        }
    }



    // Array.forEach兼容
    if ( !Array.prototype.forEach ) {
        Array.prototype.forEach = function forEach( callback, thisArg ) {
            var T, k;
            if ( this == null ) {
                throw new TypeError( "this is null or not defined" );
            }
            var O = Object(this);
            var len = O.length >>> 0;
            if ( typeof callback !== "function" ) {
                throw new TypeError( callback + " is not a function" );
            }
            if ( arguments.length > 1 ) {
                T = thisArg;
            }
            k = 0;
            while( k < len ) {
    
                var kValue;
                if ( k in O ) {
                    kValue = O[ k ];
                    callback.call( T, kValue, k, O );
                }
                k++;
            }
        };
    }

    // 校对，点击打开详情信息
    $('.error-list').on('click','>li',function(){
        var height = $(this).find('.full-view').outerHeight(true);
        var eid = $(this).attr('eid');
        $('.editor-wrapper_content .focused').removeClass("focused");
        var self = $('.editor-wrapper_content [eid='+eid+']').addClass('focused')
        
        try {
            var top = self.offset().top - 100 + $('.editor-wrapper_content').scrollTop() || 0;
            $('.editor-wrapper_content').animate({
                scrollTop:top
            },300);
        } catch(e) { }

        $(this).css({ height:height+'px'}).addClass("expand").siblings().removeClass('expand').css({height:'auto'});
    })
    
    // 删除校对
    .on('click','.pax-simple-button',function(){
        $(this).parent().parent().parent().parent().remove();
    })

    // 右侧校对监听
    .on('click','span[eid]',function(){
        var eid = $(this).attr('eid');
        var text = $(this).text();

        setTimeout(function(){
            $('.editor-wrapper_content [eid='+eid+']').text(text).removeAttr('class');
        },100);
        
        $('.error-list li.expand').remove();
    });

    // 点击左侧文字
    ;$('.editor-wrapper_content').on('click','.focuse',function(){
        $('.editor-wrapper_content .focused').removeClass('focused');
        var eid = $(this).attr('eid');
        $(".error-list li[eid="+eid+"]").click();

    })
    
    // 监听Editor粘贴
    // .on('paste',function(){
    //     setTimeout(function(){
    //         parseEditorContent();
    //     },400);
    // });


    // 格式化内容
    function parseEditorContent(){
		$(".writingtip").hide();
        var eid = 'v_9527';
        var textList = [];
        $('.editor-wrapper_content>*').each(function(i,item){
            
            var tagName = $(item).prop('tagName');

            if( tagName == 'IMG' ) {
                textList.push(['image','<img src="'+$(item).attr('src')+'" />']);
            } else {
                var images = $(item).find('img');
                if( images.length == 0 ) {
                    textList.push(['text',formatStr($(item).text())]);
                } else {
                    var i_s = '';
                    images.each(function(i,item){
                        i_s+='<img src="'+$(item).attr('src')+'" />';
                    });
                    textList.push(['image',i_s]);
                }
            }

            $(item).attr('eid',eid+i);
        });

        // console.log( textList );
        clearRightContent();
        renderEditor(textList);

        // 上传前校验
        beforeVerification(proofreading,getContentHtml(),getContentText());
    }

    // 重新渲染html
    function renderEditor(texts){
        var eid = 'v_9527';
        var html = '';
        texts.forEach(function(item,index){
            if(item[0] == 'text') {
                var text = item[1];
                text = text.replace(/>/g,'&gt;').replace(/</g,'&lt;');
                html+='<p eid="'+eid+index+'">'+text+'</p>';
            } else {
                html+='<p>'+item[1]+'</p>';
            }
        });

        $('.editor-wrapper_content').html(html);
    }

    // 校对文本
	function proofreading(){
        // 找到文本
        var t_s = [];
        
        
        $('.editor-wrapper_content [eid]').each(function(i,item){
            var text = $(item).text();
            if( !!text ) {
                t_s.push([$(item).attr('eid'),text])
            }
        });

        var success = 0;
        var length = t_s.length;
        var i = 0;

        requestHttp(t_s[0] || [],i);

        // 接口有限制 1秒最多请求3次 每隔一段时间请求一次
        var time = setInterval(function(){
            i++;
            if( i >= t_s.length ){
                onMessage && onMessage({ length:length, success: success,sop:i  });
                return clearInterval(time);
            };
            requestHttp(t_s[i],i);
        },300);

        function requestHttp(item,index){
            request(item[1],function(response){
                var eid = item[0];
                success++;
                onMessage && onMessage({ length:length, success:success, sop:index  });
                renderToText($('.editor-wrapper_content [eid='+eid+']'),response,eid);
            });
        }
    }
    function proofreading2(){
        // 找到文本
        var t_s = [];
        $('.editor-wrapper_content [eid]').each(function(i,item){
            var text = $(item).text();
            if( !!text ) {
                t_s.push([$(item).attr('eid'),text])
            }
        });

        var i = 0;
        var firstItem = t_s[0] || [];
        request(firstItem[1],function(response){
            var eid = firstItem[0];
            renderToText($('.editor-wrapper_content [eid='+eid+']'),response,eid);
        });

        // 接口有限制 1秒最多请求3次 每隔一段时间请求一次
        var time = setInterval(function(){
            i++;
            if( i >= t_s.length ){
                return clearInterval(time);
            };
            var item = t_s[i];
            
            request(item[1],function(response){
                var eid = item[0];
                renderToText($('.editor-wrapper_content [eid='+eid+']'),response,eid);
            });
            
        },300);
    }

    // 格式化字符串 去掉空格
    function formatStr(str){
        try {
            return String(str).replace(/(\r|\n|\s|&nbsp;)/g,'')
        } catch(e) {}
        return str;
    }

    // 渲染右侧校对
    function renderToText(self,response,eid){

        var revisions = response.data.corrected_sentences[0]['revisions'];
        if( !revisions ) { return }

        var html = '';
        var texts = self.text().split('');
        revisions.forEach(function(item,index){

            var eide = eid+'_'+index;
            texts = replaceStr(texts,item.position,item.length,item.string_to_correct,eide);
			 html+='<li class="fate-in" style="height: auto;" eid="'+eide+'">'+
                    '<div class="simple-view">'+
                        '<span>'+item.string_to_correct+' </span>'+
                        '<span>'+(item.error_desc_sm_zh || error_desc_sm_en)+'</span>'+
                    '</div>'+
                    '<div class="full-view">'+
                        '<div>'+
                            '<div class="correct-content">'+
                                '<span class="error-words">'+item.string_to_correct+'</span>'+
                                '<div class="candidate-words">'+
                                    correctionMap(item.correction,eide).join('')+
                                '</div>'+
                            '</div>'+
                            '<p class="correct-desc">'+(item.error_desc_zh || item.error_desc_en)+'</p>'+
                        '</div>'+
                        '<div>'+
                            '<div class="pax-popover hovering" style="width: auto;">'+
                                '<a title="忽略" class="ifx-c pax-simple-button">'+
                                    '<svg symbol="cross" size="14 14" viewBox="0 0 14 14" width="14" height="14" style="fill: currentcolor;">'+
                                        '<use xlink:href="'+config.svgURL+'?v=1.1.17#cross"></use>'+
                                    '</svg>'+
                                '</a>'+
                            '</div>'+
                        '</div>'+
                    '</div>'+
                '</li>';
            /*
            html+=`<li class="fate-in" style="height: auto;" eid="${eide}">
                    <div class="simple-view">
                        <span>${item.string_to_correct} </span>
                        <span>${ item.error_desc_sm_zh || error_desc_sm_en }</span>
                    </div>
                    <div class="full-view">
                        <div>
                            <div class="correct-content">
                                <span class="error-words">${item.string_to_correct}</span>
                                <div class="candidate-words">
                                    ${correctionMap(item.correction,eide).join('')}
                                </div>
                            </div>
                            <p class="correct-desc">${item.error_desc_zh || item.error_desc_en }</p>
                        </div>
                        <div>
                            <div class="pax-popover hovering" style="width: auto;">
                                <a title="忽略" class="ifx-c pax-simple-button">
                                    <svg symbol="cross" size="14 14" viewBox="0 0 14 14" width="14" height="14" style="fill: currentcolor;">
                                        <use xlink:href="${config.svgURL}?v=1.1.17#cross"></use>
                                    </svg>
                                </a>
                            </div>
                        </div>
                    </div>
                </li>`;
				*/

        });

        self.html( texts.join('') );
		
        $(html).appendTo('.error-list');


        function correctionMap(correction,eid){
            correction.forEach(function(item,index){
                correction[index] = '<span eid="'+eid+'">'+item+'</span>'
            });
            return correction;
        }
    }
    

    // 替换字符串
    function replaceStr(arr,position,len,str1,eid){

        if(arr.length < position + len ){ return arr }

        if(len == 1) {
            arr[position] = '<span class="focuse" eid="'+eid+'">'+str1+'</span>';
        } else if(len == 2){
            arr[position] = '<span class="focuse" eid="'+eid+'">';
            arr[position+1] = str1+'</span>';
        } else if( len == 3 ) {
            arr[position] = '<span class="focuse" eid="'+eid+'">';
            arr[position+1] = str1;
            arr[position+2] = '</span>';
        } else if(position > 3 ) {
            var po1 = position - 3;
            arr[position] = '<span class="focuse" eid="'+eid+'">';
            arr[position+1] = str1;
            arr[position+2] = '</span>';
            for( i = 0; i<po1;i++ ) {
                arr[position+3+i] = '';
            }
        }
        return arr;
    }



    

    // 请求封装
    function request(text,callback){

        if( !config.ajax.data || typeof config.ajax.data != 'object') {
            config.ajax.data = {}
        }

        //var response1 = {"code":"0","data":{"corrected_sentences":[{"corrected_sent":"","revisions":[{"correction":["香",'项'],"edit_type":"UPDATE","error_desc_en":"","error_desc_zh":"请考虑将“向”替换为“香”。","error_desc_sm_en":"修改字词","error_desc_sm_zh":"修改字词","error_type":"SPELL","length":1,"position":14,"confidence":true,"can_protect":true,"detail_type":"OTHER","string_to_correct":"向"},{"correction":["，"],"edit_type":"UPDATE","error_desc_en":"","error_desc_zh":"冒号使用不当，请考虑修改标点。","error_desc_sm_en":"冒号误用","error_desc_sm_zh":"冒号误用","error_type":"SPELL","length":1,"position":43,"confidence":true,"can_protect":false,"detail_type":"OTHER","string_to_correct":"："}],"sent_length":76,"sent_start":0,"source_sent":"花园⾥除了光彩，还有淡淡的⽅向，⾹⽓似乎也是浅紫⾊的，梦幻⼀般轻轻地笼罩着我。那时据说：花和⽣活腐化有什么必然关系。我曾遗憾地想：这⾥再看不⻅藤萝花了。"}]},"msg":"success"}

        //return callback && callback(response1);
		
        config.ajax.data.text = text;
		config.ajax.data.id = $("#ID").val(); //新增加
        config.ajax.success = function(response){
            if(response.code == config.ajaxSuccessCode) {
                callback && callback(response);
            }
        }
        $.ajax(config.ajax);
    }


    function setContentHtml(html){
        $(".editor-wrapper_content").html(html);
        writing.parseEditor();
    }
    function getContentHtml(){
        return $(".editor-wrapper_content").html()
    }
    function getContentText(){
        return $(".editor-wrapper_content").text()
    }
    function clearRightContent(){
        $('.error-list').html('');
    }
    
    // request('花园⾥除了光彩，还有淡淡的⽅香。',function(response){
    //     console.log(response);
    // })

})(window,this);